package com.dldata.devtools30.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dldata.devtools30.businessmodel.QueryResult;
import com.dldata.devtools30.cfg.ApplicationHome;
import com.dldata.devtools30.common.EnumOrganization;
import com.dldata.devtools30.entity.DevtModelOrganizationEntity;
import com.dldata.devtools30.entity.DevtModelReleaselogEntity;
import com.dldata.devtools30.utils.DateUtil;
import com.dldata.devtools30.utils.FileUtils;
import com.dldata.devtools30.utils.Public;
import com.dldata.devtools30.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.persistence.Table;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by 呵呵 on 2017-12-13.
 */
@Controller
@RequestMapping(value = "/ReleaseAndImportController")
@Slf4j
public class ReleaseAndImportController extends DevBase30Controller {
    
    @RequestMapping(value = "submitCloneCfgData")
    @ResponseBody
    public Result submitCloneCfgData(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String desthospitalversion = req.getParameter("desthospital");
        EnumOrganization destenumOrganizations =EnumOrganization.getInstanceFromName(desthospitalversion);
        if(destenumOrganizations==null){
            return Result.error("系统不包含该机构."+desthospitalversion);
        }
    
        String designdatadir=ApplicationHome.getApplicationConfig()+"/designdata";
        String jgdatadir=designdatadir+"/"+destenumOrganizations.getCode();
        if(!new File(jgdatadir).exists()){
            new File(jgdatadir).mkdirs();
        }
        
        DevtModelOrganizationEntity destorganizationEntity=new DevtModelOrganizationEntity();
        destorganizationEntity.setId(UUID.randomUUID().toString());
        destorganizationEntity.setCode(destenumOrganizations.getCode());
        destorganizationEntity.setName(destenumOrganizations.getName());
        destorganizationEntity.setFormversion(DateUtil.formatFromDate(DateUtil.FORMATER_YYYYMMDDHHMMSS,new Date()));
        destorganizationEntity.setReleasetime(new Timestamp(System.currentTimeMillis()));
        
        ArrayList<Class> configtablenamesList=new ArrayList();
        configtablenamesList.addAll(Public.configTableEntitysExt);
        configtablenamesList.addAll(Arrays.asList( Public.configTableEntitys));
        for (int i = 0; i < configtablenamesList.size(); i++) {
            Class configtablename = configtablenamesList.get(i);
            Table annotation = (Table)configtablename.getDeclaredAnnotation(Table.class);
            List resultlist = commonApiDao.getScrollData(configtablename).getResultlist();
            if(configtablename.equals(DevtModelOrganizationEntity.class)){
                resultlist.clear();
                resultlist.add(destorganizationEntity);
            }
            if(configtablename.equals(DevtModelReleaselogEntity.class)){
                resultlist.clear();
                DevtModelReleaselogEntity sysModelReleaselogEntity=new DevtModelReleaselogEntity();
                sysModelReleaselogEntity.setId(UUID.randomUUID().toString());
                sysModelReleaselogEntity.setFormversion(destorganizationEntity.getFormversion());
                sysModelReleaselogEntity.setReleasetime(destorganizationEntity.getReleasetime());
                sysModelReleaselogEntity.setCode(destorganizationEntity.getCode());
                sysModelReleaselogEntity.setName(destorganizationEntity.getName());
                resultlist.add(sysModelReleaselogEntity);
            }
            FileUtils.write(new File(jgdatadir,annotation.name().toLowerCase(Locale.ROOT)+".json"),
                    JSON.toJSONString(resultlist,SerializerFeature.PrettyFormat, SerializerFeature.SortField, SerializerFeature.UseISO8601DateFormat),
                    "UTF-8");
        }
        
        return Result.ok("导出成功,git提交导出的表单配置数据."+jgdatadir);
    }
    
    
    @RequestMapping(value = "releasedata")
    @ResponseBody
    public Result releasedata(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<DevtModelOrganizationEntity> organizationEntityList = commonApiDao.getScrollData(DevtModelOrganizationEntity.class).getResultlist();
        if(organizationEntityList.size()>1){
            return Result.error("机构表只允许一行数据.");
        }
        
        String designdatadir=ApplicationHome.getApplicationConfig()+"/designdata";
        if(!new File(designdatadir).exists()){
            new File(designdatadir).mkdirs();
        }
    
        DevtModelOrganizationEntity organizationEntity = organizationEntityList.get(0);
        EnumOrganization enumOrganizations =EnumOrganization.getInstanceFromName(organizationEntity.getName());
        if(enumOrganizations==null){
            return Result.error("不包含该机构."+ organizationEntity.getName());
        }
    
        organizationEntity.setReleasetime(new Timestamp(System.currentTimeMillis()));
        organizationEntity.setFormversion(DateUtil.formatFromDate(DateUtil.FORMATER_YYYYMMDDHHMMSS,new Date()));
        commonApiDao.save(organizationEntity);
        DevtModelReleaselogEntity releaselogEntity=new DevtModelReleaselogEntity();
        releaselogEntity.setId(UUID.randomUUID().toString());
        releaselogEntity.setCode(organizationEntity.getCode());
        releaselogEntity.setName(organizationEntity.getName());
        releaselogEntity.setReleasetime(organizationEntity.getReleasetime());
        releaselogEntity.setFormversion(organizationEntity.getFormversion());
        commonApiDao.save(releaselogEntity);
        
        String jgdatadir=designdatadir+"/"+enumOrganizations.getCode();
        ArrayList<Class> configtablenamesList=new ArrayList();
        configtablenamesList.addAll(Public.configTableEntitysExt);
        configtablenamesList.addAll(Arrays.asList( Public.configTableEntitys));
        for (int i = 0; i < configtablenamesList.size(); i++) {
            Class configtablename = configtablenamesList.get(i);
            Table annotation = (Table)configtablename.getDeclaredAnnotation(Table.class);
            List resultlist = commonApiDao.getScrollData(configtablename).getResultlist();
            FileUtils.write(new File(jgdatadir,annotation.name().toLowerCase(Locale.ROOT)+".json"),
                    JSON.toJSONString(resultlist,SerializerFeature.PrettyFormat, SerializerFeature.SortField, SerializerFeature.UseISO8601DateFormat),
                    "UTF-8");
        }
        
        return Result.ok("导出成功,git提交导出的表单配置数据."+jgdatadir);
    }
    
    
    @RequestMapping(value = "importdata")
    @ResponseBody
    public Result importdata(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String hospitalversion = req.getParameter("hospitalversion");
        
        String designdatadir=ApplicationHome.getApplicationConfig()+"/designdata";
    
        EnumOrganization enumOrganizations =EnumOrganization.getInstanceFromName(hospitalversion);
        if(enumOrganizations==null){
            return Result.error("系统不包含该机构."+hospitalversion);
        }
        
        String jgdatadir=designdatadir+"/"+enumOrganizations.getCode();
        if(!new File(jgdatadir).exists()){
            return Result.error("数据目录不存在."+hospitalversion+" , "+jgdatadir);
        }
        
        try{
            ArrayList<Class> configtablenamesList=new ArrayList();
            configtablenamesList.addAll(Public.configTableEntitysExt);
            configtablenamesList.addAll(Arrays.asList( Public.configTableEntitys));
            for (int i = 0; i < configtablenamesList.size(); i++) {
                Class configtablename = configtablenamesList.get(i);
                Table annotation = (Table)configtablename.getDeclaredAnnotation(Table.class);
                File file = new File(jgdatadir, annotation.name().toLowerCase() + ".json");
                String contentJson =!file.exists()?"[]":FileUtils.readFileToString(file, "UTF-8");
                List parseArray = JSON.parseArray(contentJson, configtablename, Feature.AllowISO8601DateFormat);
            }
        }catch (Throwable throwable){
            throwable.printStackTrace();
            return Result.error("JSON数据解析异常."+hospitalversion+" , "+jgdatadir);
        }
        
        Table annotationOrg = (Table) DevtModelOrganizationEntity.class.getDeclaredAnnotation(Table.class);
        String contentJsonOrg = FileUtils.readFileToString(new File(jgdatadir, annotationOrg.name().toLowerCase() + ".json"), "UTF-8");
        List<DevtModelOrganizationEntity> parseArrayOrg = JSON.parseArray(contentJsonOrg, DevtModelOrganizationEntity.class, Feature.AllowISO8601DateFormat);
        if(parseArrayOrg.size()!=1){
            return Result.error("机构表只允许一行数据.");
        }
        if(!hospitalversion.equals(parseArrayOrg.get(0).getName())){
            return Result.error("机构名称不匹配.请核对json文件sys_crf_form_organization表里的机构名称与选择配置的机构名称.");
        }
    
        ArrayList<Class> configtablenamesList=new ArrayList();
        configtablenamesList.addAll(Public.configTableEntitysExt);
        configtablenamesList.addAll(Arrays.asList( Public.configTableEntitys));
        List deleteObjList=new ArrayList();
        List insertObjList=new ArrayList();
        for (int i = 0; i < configtablenamesList.size(); i++) {
            Class configtablename = configtablenamesList.get(i);
            List resultlist = commonApiDao.getScrollData(configtablename).getResultlist();
            deleteObjList.addAll(resultlist);
            Table annotation = (Table)configtablename.getDeclaredAnnotation(Table.class);
            File file = new File(jgdatadir, annotation.name().toLowerCase() + ".json");
            String contentJson =!file.exists()?"[]":FileUtils.readFileToString(file, "UTF-8");
            List parseArray = JSON.parseArray(contentJson, configtablename, Feature.AllowISO8601DateFormat);
            insertObjList.addAll(parseArray);
        }
        
        commonApiDao.batchDelete(deleteObjList);
        commonApiDao.batchSave(insertObjList);
        return Result.ok("导出成功,git提交导出的表单配置数据.");
    }
    
    @RequestMapping(value = "releaselog")
    @ResponseBody
    public Result releaselog(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("releasetime","desc");
        QueryResult<DevtModelReleaselogEntity> queryResult
                = commonApiDao.getScrollData(DevtModelReleaselogEntity.class, 0, 3000, linkedHashMap);
        List<DevtModelReleaselogEntity> resultlist = queryResult.getResultlist();
        List<HashMap> dataList=new ArrayList<>();
        for (int i = 0; i < resultlist.size(); i++) {
            DevtModelReleaselogEntity releaselogEntity = resultlist.get(i);
            HashMap hashMap=JSON.parseObject(JSON.toJSONString(releaselogEntity),HashMap.class);
            hashMap.put("releasetimeshow",DateUtil.formatFromDate(DateUtil.FORMATER_YYYY_MM_DD_HH_MM_SS,releaselogEntity.getReleasetime()));
            dataList.add(hashMap);
        }
        return Result.ok("查询成功.", dataList);
    }
}
